package com.tangula.android.kashine.application

import android.annotation.SuppressLint
import android.app.Application
import android.os.AsyncTask
import android.util.Log
import com.tangula.android.kashine.R
import com.tangula.android.kashine.broadcast.db.DbInitEndBroadcast
import com.tangula.android.kashine.db.KashineDbCreator
import com.tangula.android.kashine.entity.AccountEntity
import com.tangula.android.orm.BaseDataBaseHelper
import com.tangula.android.orm.ContextSupplier
import com.tangula.android.orm.Entity
import org.xmlpull.v1.XmlPullParser

/**
 * Kashine應用程序.
 */
class KashineApplication : Application() {

    /**
     * 數據是是否已經準備好了.
     */
    var databaseReady = false

    init {
        KashineApplication.CURRENT_APP = this
    }

    override fun onCreate() {
        super.onCreate()
        initDatabase()

    }

    /**
     * 初始化數據庫.
     */
    private fun initDatabase() {
        BaseDataBaseHelper.CONTEXT_FAC = ContextSupplier { getCurrentApplication() }

        //初始化结束后，设置数据库就绪状态为true
        DbInitEndBroadcast(this) { _, _ ->
            databaseReady = true
        }

        BaseDataBaseHelper.setDbCreator(KashineDbCreator())

        //异步执行数据库初始化
        val initTask = @SuppressLint("StaticFieldLeak")
        object : AsyncTask<Unit, Int, Unit>() {
            override fun doInBackground(vararg params: Unit?) {
                if (BaseDataBaseHelper.getDatabase() != null) {

                    val xml = KashineApplication.getCurrentApplication().resources.getXml(R.xml.entities)
                    //根据xml配置初始化数据库
                    var event_type = xml.eventType
                    while (event_type != XmlPullParser.END_DOCUMENT) {
                        when (event_type) {
                            XmlPullParser.START_TAG ->
                                when (xml.name) {
                                    "entity" -> {
                                        val class_name = xml.getAttributeValue(null, "class")
                                        val force = xml.getAttributeBooleanValue(null, "force", false)
                                        val entity_class = Class.forName(class_name)
                                        Log.v("console","will create entity table for class: $class_name and force: $force")
                                        BaseDataBaseHelper.createTable(
                                                entity_class as Class<out Entity<String>>,
                                                force
                                        )
                                    }
                                }
                        }


                        event_type = xml.next()
                    }

                    DbInitEndBroadcast.send(getCurrentApplication())
                }
            }
        }
        initTask.execute(null)

    }

    companion object {
        @JvmStatic
        private var CURRENT_APP: KashineApplication? = null

        @JvmStatic
        fun getCurrentApplication(): KashineApplication {
            return CURRENT_APP!!
        }

        fun getCurrentAccount(): AccountEntity {
            return AccountEntity().also {

            }
        }
    }

}